/**
 *Project: jh-framework
 *File: cn.xkshow.commons.http.HttpClientHandle.java 
 *Author: admin@xkshow.cn with the copyrite
 ****************************************************************
 *   VERSION       DATE            BY       CHANGE/COMMENT
 * --------------------------------------------------------------
 *    1.0        2013-4-11        xkshow.cn         create
 ****************************************************************
 *note:
 ***************************************************************/
package cn.xkshow.commons.http;

import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.GetMethod;

import cn.xkshow.commons.logging.LoggerBase;

public class HttpClientHandle extends LoggerBase {
	private static HttpClientHandle instance = null;

	private HttpClientHandle() {
	}

	public static HttpClientHandle getInstance() {
		if (null == instance) {
			instance = new HttpClientHandle();
		}
		return instance;
	}

	/**
	 * Format the results
	 * @param: url, data
	 */
	public String getStringByResult(String method, String url,
			NameValuePair[] data) {
		return this.doPost(url, data);
	}

	public JSONObject getJsonObjectByResult(String method, String url,
			NameValuePair[] data) {
		String result = this.doPost(url, data);
		result = result.substring(1, result.length() - 1);

		return JSONObject.fromObject(result);
	}

	public Map<String, String> getJson2MapByResult(String method, String url,
			NameValuePair[] data) {
		Map<String, String> retMap = new HashMap<String, String>();
		String result = this.doPost(url, data);
		result = result.substring(1, result.length() - 1);
		JSONArray json = JSONArray.fromObject(result);
		logger.debug(json);

		JSONObject obj = null;
		for (int i = 0; i < json.size(); i++) {
			result = json.get(i).toString();
			obj = JSONObject.fromObject(result);
			retMap.put(result, obj.get("mid").toString());
		}
		return retMap;
	}
	

	/**
	 * doMethod: post/get
	 * @param: method, url(Agreement://), data
	 * @return: getResponseBodyAsString
	 */
	private String doMethod(String method, String url, NameValuePair[] data) {
		if(null!=method && method.equalsIgnoreCase("POST")){
			return doPost(url, data);
		}else{//default:get
			return doGet(url, data);
		}
	}
	private String doPost(String url, NameValuePair[] data) {
		logger.info("HttpClientHandle: doPost: ");
		String result = "";
		try {
			// 建立HttpClient对象
			HttpClient httpClient = new HttpClient();
			// 模拟Post请求方式
			PostMethod postMethod = new PostMethod(url);
			// 参数
			if(null != data){
				postMethod.setRequestBody(data);
			}

			// 设置 HttpClient接收 Cookie,用与浏览器一样的策略
			httpClient.getParams().setCookiePolicy(
					CookiePolicy.BROWSER_COMPATIBILITY);
			httpClient.executeMethod(postMethod);

			result = postMethod.getResponseBodyAsString();
		} catch (Exception e) {
			// TODO: handle exception
			logger.error("HttpClientHandle.doPost(): 异常: " + e);
			result = "({'code':'error'})";
		} finally {
			return result;
		}
	}
	private String doGet(String url, NameValuePair[] data) {
		logger.info("HttpClientHandle: doGet: ");
		String result = "";
		try {
			// 建立HttpClient对象
			HttpClient httpClient = new HttpClient();
			// 模拟 Get请求方式
			GetMethod getMethod = new GetMethod(url);
			
			// 设置 HttpClient接收 Cookie,用与浏览器一样的策略
			httpClient.getParams().setCookiePolicy(
					CookiePolicy.BROWSER_COMPATIBILITY);
			httpClient.executeMethod(getMethod);

			result = getMethod.getResponseBodyAsString();
		} catch (Exception e) {
			// TODO: handle exception
			logger.error("HttpClientHandle.getMethod(): 异常: " + e);
			result = "({'code':'error'})";
		} finally {
			return result;
		}
	}

}
